package http;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Objects;

/**
 * tomcat
 *
 * @author 50238
 */
public class MyTomcat {
    private static final int PORT = 8080;
    private RequestMapping requestMapping;

    {
        //初始化request请求地址
        requestMapping = new RequestMapping();
    }

    /**
     * 启动类
     */
    public void start() {
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(PORT);
            //while保持长时间连接
            while (true) {
                //注意这里try catch保证catch到所有错误保证程序不停止
                try {
                    Socket accept = serverSocket.accept();
                    InputStream inputStream = accept.getInputStream();
                    OutputStream outputStream = accept.getOutputStream();
                    Request request = Request.create(inputStream);
                    Response response = Response.create(outputStream);
                    requestMapping.dispatch(request, response);
                    accept.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //保证连接关闭
            if (Objects.nonNull(serverSocket)) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
